<?php

use com\gdl\newagk\interfaces\AdminpaperServiceIf;
use com\gdl\common\dataobject\common\ResultDO;
use com\gdl\newagk\dataobject\adminpaper\AdminpaperDTO;
use com\gdl\newagk\dataobject\adminpaper\AdminpaperRequestDTO;


class api_AdminpaperService extends api_Abstract implements AdminpaperServiceIf
{

	//添加试卷
    public function add(AdminPaperRequestDTO $basic)
    {
		$result = new ResultDO();
		$datas = $basic->filename ? $basic->filename : [];
			
		try{
			$result->code = 0;
			$result->success = true;
			/*****/
		    if(empty($datas['creditsettingid'])){
                $datas['scores'] = 0;
            }
            if(empty($datas['settings'])){
				 $result->message = "请填写规则";
				 return $result;
			}
			
			if (empty($datas['name'])) {
					
					$result->message = "缺少试卷名";
					return $result;
				
			}
			
			$ratio = $datas['settings'] = json_decode($datas['settings'],true); //因为定义的只是一个以为数组所以传过来的数据json化了
            $ra_temp = 0;
			/*
           if($datas['per'] ==2){//高级模式
                $ob_dw = new DrawQuestion();
                $ratio = $ob_dw->enRation($datas['ratio']);
                $ratio = $ob_dw->deRation($ratio,3);
            }*/

			$paper = new model_newagk_paper();
			$papers = $paper->selectOne(['name'=>$datas['name']],'id');
			if (!empty($papers['id'])){
               
				 $result->message = "试卷名已存在";
				 return $result;
            }
			
            foreach($ratio as $val){
                $ra_temp += (int)$val[3]*(int)$val[4];
            }
            if ($ra_temp>$datas['totalScore']){
               
				 $result->message = "您的规则总分不能超过试卷总分";
				 return $result;
            }
          
			$result_txt  =self::s_save($datas);

			if ($result_txt!='y') {

					$result->message = $result_txt;
					return $result;

			}
			
			/******/
				$result->message ='成功';
                $result->code = 1;
            
            
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = 0;
            $result->message = '异常';
        }
        return $result;
    }
	
	//查看试卷配置
	 public function lookOver(AdminpaperDTO $basic)
    {
			$result = new ResultDO();
			$id = $basic->id ? gdl_lib_BaseUtils::getStr($basic->id,'int') : 0;
			$platform_id = $basic->platform_id ? gdl_lib_BaseUtils::getStr($basic->platform_id,'int') : 0;

		try{
			/**********/
			$result->code = 0;
            $result->success = true;
            if(!$id || !$platform_id){
				$result->message = "缺少参数ID";
				return $result;
			}
			$paper = new model_newagk_paper();
			$labels = new model_newagk_labels();
			$sections = new model_newagk_sections();
			$qbank = new model_newagk_qbank();
			$paperArr = $paper->selectOne(['id'=>$id],'id,name,dbs,duration,totalScore,passScore,puse,paperType,settings,status,shared,labelId');
			if(empty($paperArr)){
				$result->message = "记录不存在";
			} else {
				$result->code = 1;
				$cloud_staus=1;
				$inherit = $paper->fatherfo($platform_id);
				if($paperArr['status']==3){
					$cloud_staus = 4;
				} else if(empty($inherit[$paperArr['id']])){
					$cloud_staus = 3;
				} else if(!empty($inherit[$paperArr['id']]) && $inherit[$paperArr['id']]['version']){
					$cloud_staus = 2;
				}
			
				$sectionArr = $sections->sectionArr($paperArr['dbs']);
				$chooseid = $paper->getInfoArgLabelId($id);
				$paperid = [0];
				$selectPaperid = [0];
				foreach($chooseid as $k=>$v){
					$paperid[] = $k;
					$selectPaperid[] = $v;
				}
			
				$labelist = $labels->getInfoArgDetails(implode(',',$paperid),$selectPaperid);

				foreach($labelist as $kl=>$vl){
					$vl['chid'] = empty($chooseid[$kl]) ? 0 : $chooseid[$kl];
			
				}
				
			
				$settings = unserialize($paperArr['settings']);
				$ratio = [];
				foreach($settings as $v){
					$scoreOne = $v[3]*$v[4];
					$questioNum+=$v[3];
					$score+=$scoreOne;
					$v[0] = (int)$v[0];
					$v[1] = (int)$v[1];
					$v[2] = (int)$v[2];
					$v[3] = (int)$v[3];
					$v[4] = (float)$v[4];
					$v[5] = (int)$v[5];
					$v[7] = empty($sectionArr[$v[2]]) ? '全部章节' : $sectionArr[$v[2]];
					$v[6] = $scoreOne;
					$ratio[] = $v;
				}
				$qbankDeil = $qbank->selectOne(['id'=>$paperArr['dbs']],'name');
				$datas['labelId']=json_encode($labelist);
				$datas['title']=htmlspecialchars_decode($paperArr['name']);
				$datas['qbankid']=$paperArr['dbs'];
				$datas['qbankName']=empty($qbankDeil['name']) ? '未知' : $qbankDeil['name'];
				$datas['total_time']=$paperArr['duration']/60;
				$datas['total_score']=$paperArr['totalScore'];
				$datas['pass_score']=$paperArr['passScore'];
				$datas['typesof']=$paperArr['puse'];
				$datas['problemet']=$paperArr['paperType'];
				$datas['ratio']=serialize($ratio);
				$datas['status']=$paperArr['status'];
				$datas['shared']=$paperArr['shared'];
				$datas['cloud_staus']=$cloud_staus;
				$datas['questioNum']=(int)$questioNum;
				$datas['score']=$score;
				$result->data[] = $datas;
			}
            /*********/
        
    
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }
	//修改试卷配置
	 public function edit(AdminPaperRequestDTO $basic)
    {
		$result = new ResultDO();
		$datas = $basic->filename ? $basic->filename : [];
		if(empty($datas['id'])){
				 $result->message = "修改失败";
				 return $result;
		}	
		try{
			$result->code = 0;
			$result->success = true;
			/*****/
		    if(empty($datas['creditsettingid'])){
                $datas['scores'] = 0;
            }
            if(empty($datas['settings'])){
				 $result->message = "请填写规则";
				 return $result;
			}
			$ratio = $datas['settings'] = json_decode($datas['settings'],true); //因为定义的只是一个以为数组所以传过来的数据json化了
            $ra_temp = 0;
			/*
           if($datas['per'] ==2){//高级模式
                $ob_dw = new DrawQuestion();
                $ratio = $ob_dw->enRation($datas['ratio']);
                $ratio = $ob_dw->deRation($ratio,3);
            }*/

            foreach($ratio as $val){
                $ra_temp += (int)$val[3]*(int)$val[4];
            }
            if ($ra_temp>$datas['totalScore']){
               
				 $result->message = "您的规则总分不能超过试卷总分";
				 return $result;
            }
         
			$result_txt  =self::s_save($datas);
			
			if ($result_txt!='y') {
					$result->message =$result_txt;
					return $result;
				
			}
			$paper = new model_newagk_paper();
			$paper->update(['father'=>$id],"version=1");
			/******/
				$result->message = '成功';
                $result->code = 1;
            
            
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
	}
	
	//统计试卷数量
    public function numPapers(AdminpaperDTO $basic)
    {
		$result = new ResultDO();
		$reg = $basic->reg ? $basic->reg : '';
			
		try{
			$result->code = 0;
			$result->success = true;
			/*****/
		    if($reg==''){
				 $result->message = "缺少参数";
				 return $result;
			}
			$num = ['1'=>0,'2'=>0,'3'=>0,'totals'=>0];//'1'=>模拟,'2'=>正式,'3'=>公用 
			$paper = new model_newagk_paper();
			$papersNum = $paper->select(['isdelete'=>0,'status'=>1],'count(*) num,puse','','group by puse')->items;
			foreach($papersNum as $v){
				$num[$v['puse']] = $v['num'];
				$num['totals']+= $v['num'];
			}
			
			/******/
				$result->data[] = $num;
				$result->message ='成功';
                $result->code = 1;
            
            
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = 0;
            $result->message = '异常';
        }
        return $result;
    }
	
	
	//试卷列表
	 public function paperlist(AdminPaperRequestDTO $basic)
    {
		$result = new ResultDO();
		$filename = $basic->filename ? $basic->filename : [];
		$qid = $basic->filename['qid'] ?  gdl_lib_BaseUtils::getStr($basic->filename['qid'], 'int') : 0;
		$typesof = $basic->filename['typesof'] ?  gdl_lib_BaseUtils::getStr($basic->filename['typesof'], 'int') : '';
		$problemet = $basic->filename['problemet'] ?  gdl_lib_BaseUtils::getStr($basic->filename['problemet'], 'string') : ''; 
		$shared = $basic->filename['shared'] ?  gdl_lib_BaseUtils::getStr($basic->filename['shared'], 'string') : '';
		$platform = $basic->filename['platform'] ?  gdl_lib_BaseUtils::getStr($basic->filename['platform'], 'string') : '';
		$title = $basic->filename['title'] ?  gdl_lib_BaseUtils::getStr($basic->filename['title'], 'string') : '';
		$status = $basic->filename['status'] ?  gdl_lib_BaseUtils::getStr($basic->filename['status'], 'int') : '';
		$down = $basic->filename['down'] ?  $basic->filename['down'] : '';
		$downid = $basic->filename['id'] ?  explode(',',$basic->filename['id']) : '';
		$spec = $basic->filename['spec'] ?  1 : 0;
		
		$paper = [];
			if(empty($basic->filename['del'])){
				$condition = 'isdelete=0';
			} else {
				$condition = 'isdelete=1';
			}
  
            //$userid = $userid ? gdl_lib_BaseUtils::getStr($userid, 'int') : 0;
			$platform_id = $platform_id ? gdl_lib_BaseUtils::getStr($platform_id, 'int') : 0;
			//现在还没有启动平台id 所以下面只接差所有
			$modelPlaform = new model_newagk_platform();
			$paper = new model_newagk_paper();
			$qbank = new model_newagk_qbank();
			//名称/云试卷来源关键字

			if($title!=''){
				$inherit = $paper->select("name like '%{$title}%'",'id')->items;
				$id = [];
				foreach($inherit as $v){
					$id[] = $v['id'];
				}
				$condition .= " and ( name like '%{$title}%'";
				if(!empty($id)) $condition .= ' or father in('.implode(',',$id).')';
				$condition .= ' )';
			}
			
			//试卷来源题库
			if($qid){
				$condition .= ' and dbs='.$qid;
			}
			
			//试卷用途类型
			
			if($spec){
				/**强制 试卷只查询公共和正式试卷**/
				$condition .= " and puse>1";
			} else if($typesof){
				$condition .= ' and puse='.$typesof;
			}
			
			//抽题方式
			if($problemet=='fixed'){
				$condition .= ' and paperType=2';
			} else if($problemet=='randoms'){
				$condition .= ' and paperType=1';
			}
			
			//试卷状态
			if($status==1){
				$condition .= ' and status=1';
			} else if($status==2){
				$condition .= ' and status=2';
			} else if($status==3){
				$condition .= ' and status=3';
			}
			//是否共享
			if($shared=='shareit'){
				$condition .= ' and shared=1';
			} else if($shared=='noshare'){
				$condition .= ' and shared=0';
			}
			//试卷所属平台
			/*
			if($platform){
				$reg = $modelPlaform->getChildAdminRegByPlaformId($platform_id,$platform);
				$condition .= " and admin_reg in('".implode("','",$reg)."')";
			}
			*/
			
			if($platform){
				$adminreg = $modelPlaform->select("status=1 and reals like '%{$platform}%'",'admin_reg')->items;
				$admin_reg=[1];
				foreach($adminreg as $v){
					$admin_reg[] = $v['admin_reg'];
				}
				if(!empty($admin_reg[0])){
					$condition .= " and admin_reg in('".implode("','",$admin_reg)."')";
				}
			}
			
			//////////////////
			$page = ($filename['page']-1) * $filename['pagesize'];
			$items = 'id,name,dbs,puse,status,paperType,updateTime,shared,father,version,admin_reg';
			if($down=='excels'){
				$groupBy = ' order by id desc';
			} else {
				$groupBy = ' order by id desc  limit '.$page.','.$filename['pagesize'];
			}
			if($down=='excels' && !empty($downid) ){
				$dow_id = [0];
				foreach($downid as $v){
					$dow_id[] = intval($v);
				}
				$condition = ' id in('.implode(',',$dow_id).')';
			}
			
            try {
				$num = $paper->selectOne($condition, 'count(*) num');
                $res = $paper->select($condition, $items, $groupBy)->items;
				
				
				
                //进行平台顶级读取处理

                if (!empty($res)) {
					$qbank_name = $qbank->getListByArgName($platform_id);
					$typesof = ['1'=>'模拟试卷','2'=>'正式试卷','3'=>'公用试卷'];
					$status=['1'=>'启用','2'=>'禁用','3'=>'平台禁用'];
					$platform_name = $modelPlaform->getListByArgName($platform_id);
					$papers = $paper->select('isdelete=0','id,name,version')->items;
					$paper_name = [];
					foreach($papers as $vc){
						$paper_name[$vc['id']] = ['name'=>$vc['name'],'version'=>$vc['version']];
					}
					$papersa = [];
					if($down=='excels'){
							foreach($res as $v){
								$father = $v['father'] ? '云试卷' : '自建试卷';
								$father_name = '自建试卷';
								if($v['father']) $father_name = empty($paper_name[$v['father']]) ? '未知' : $paper_name[$v['father']]['name'];
								$papersa[] = [
										'id'=>$v['id'],
										'paper_name'=>$v['name'].'【'.$father.'】',
										'bank_name'=>empty($qbank_name[$v['dbs']]) ? '未知' : $qbank_name[$v['dbs']],
										'typesof'=>$typesof[$v['puse']],
										'paperType'=>$v['paperType']==2 ? '固定抽题' : '随机抽题',
										'updateTime'=>$v['updateTime'],
										'status_name'=>empty($status[$v['status']]) ? '未知' : $status[$v['status']],
										'shared'=>$v['shared'] ? '共享' : '未共享',
										'father'=>$father_name,
										'platform_name'=>empty($platform_name[$v['admin_reg']]) ? '未知' : $platform_name[$v['admin_reg']],
										];
							}
					} else {
						foreach($res as $v){
							$papersa[] = [
										'id'=>$v['id'],
										'paper_name'=>htmlspecialchars_decode($v['name']),
										'paper_type'=>$v['father']>0 ? 1 : 0,
										'bank_name'=>empty($qbank_name[$v['dbs']]) ? '未知' : $qbank_name[$v['dbs']],
										'typesof'=>$typesof[$v['puse']],
										'updateTime'=>$v['updateTime'],
										'status_name'=>$status[$v['status']],
										'status'=>$v['status'],
										'shared'=>$v['shared'],
										'paperType'=>$v['paperType']==2 ? '固定抽题' : '随机抽题',
										'father'=>empty($paper_name[$v['father']]) ? '未知' : htmlspecialchars_decode($paper_name[$v['father']]['name']),
										'replaces'=>$v['version'],
										'platform_name'=>empty($platform_name[$v['admin_reg']]) ? '未知' : $platform_name[$v['admin_reg']],
										];
						}
					}
					if(empty($papersa)){
						$result->data[] = $papersa;
					} else {
                    $result->data = $papersa;
					}
					$result->message = $num['num'];
                    $result->code = 1;

                } else {
			
                    $result->code = 1;
					 $result->message = 0;
                }
                $result->success = true;
                return $result;
            } catch (Exception $e) {
                $result->success = false;
                $result->code = $e->getCode();
                $result->message = $e->getMessage();
            }
            return $result;

	}
	
	//重新生成试卷
	public function generate(AdminpaperDTO $basic)
    {
		$result = new ResultDO();
		$id = $basic->id ? gdl_lib_BaseUtils::getStr($basic->id,'int') : 0;
		$platform_id = $basic->platform_id ? gdl_lib_BaseUtils::getStr($basic->platform_id,'int') : 0;
		
	try {
		if (!$id || !$platform_id){
				$result->code = 0;
				$result->message = '缺少必要参数';
				$result->success = true;
				return $result;
			}
			$paper = new model_newagk_paper();
			$paperArr = $paper->selectOne(['id'=>$id],'settings,dbs');
			
			
		

                if (!empty($paperArr)) {

					$drawquestion = new service_drawquestion();
					$datas = $drawquestion->randomDrawQues($paperArr['dbs'],$paperArr['settings'],1);
			
					if(empty($datas)){
						$result->code = 0;
						$result->message = '没有试题，生成失败';
					} else {
						$datas = serialize($datas);
						$paper->update(['id'=>$id],"datas='{$datas}'");
						$result->message ='成功';
						$result->code = 1;
					}
                } else {
                    $result->code = 0;
					$result->message = '记录不存在';
                }
                $result->success = true;
                return $result;
            } catch (Exception $e) {
                $result->success = false;
                $result->code = $e->getCode();
                $result->message = $e->getMessage();
            }
            return $result;
	}
	
	//查看试卷
	public function lookPaper(AdminpaperDTO $basic)
    {
		$result = new ResultDO();
		$id = $basic->id ? gdl_lib_BaseUtils::getStr($basic->id,'int') : 0;
		$platform_id = $basic->platform_id ? gdl_lib_BaseUtils::getStr($basic->platform_id,'int') : 0;
		if(!$id || !$platform_id){
			$result->code = 0;
			$result->message = '缺少必要参数';
			$result->success = true;
            return $result;
			
		}
	try {
			$paper = new model_newagk_paper();
			$qbank = new model_newagk_qbank();
			$paperArr = $paper->selectOne(['id'=>$id],'dbs,paperType,datas,settings,duration,totalScore,passScore,name');
			$qbank_name = $qbank->selectOne(['id'=>$paperArr['dbs']],'name');
			
			
			
			if($paperArr['paperType']==2){

				$result->data[][] = 1;
				$msg = unserialize($paperArr['datas']);
			} else {
				$drawquestion = new service_drawquestion();
				$result->data[][] = 2;
				//$msg = $drawquestion->randomDrawQues($paperArr['dbs'],$paperArr['settings'],1);

					//['typeId'=>'1','level'=>'1','sectionId'=>'148','scoe'=>4],

				//$msg = $ob_dw->enRation($msg);
              //  $ratio = $ob_dw->deRation($ratio,3);

				$msg = $drawquestion->randomDrawQues($paperArr['dbs'],$paperArr['settings'],1);
				//$result->message = json_encode(unserialize($paperArr['settings']));
				if($msg==false) $msg=[];
			}
				$count=0;
				foreach($msg as $vm){
					$count+=count($vm);
				}
				$datac= ['list'=>$msg,'count'=>$count,'qbankName'=>$qbank_name['name'],'duration'=>$paperArr['duration'],'totalScore'=>$paperArr['totalScore'],'passScore'=>$paperArr['passScore'],'paperName'=>$paperArr['name'],];
				$result->message = json_encode($datac);

                if (!empty($paperArr)) {

                    
					//$result->message = 0;
                    $result->code = 1;

                } else {
                    $result->code = 0;
					$result->message = 0;
                }
                $result->success = true;
                return $result;
            } catch (Exception $e) {
                $result->success = false;
                $result->code = $e->getCode();
                $result->message = $e->getMessage();
            }
            return $result;
	}

    //查看个人考试试卷
    public function lookExamsPaper(AdminpaperDTO $basic)
    {
        $result = new ResultDO();
        $id = $basic->id ? gdl_lib_BaseUtils::getStr($basic->id,'int') : 0;
        $identity_id = $basic->platform_id ? gdl_lib_BaseUtils::getStr($basic->platform_id,'int') : 0;
        if(!$id){
            $result->code = 0;
            $result->message = '缺少必要参数';
            $result->success = true;
            return $result;

        }
        $datac = array();
        try {
            $examspaper_model = new model_newagk_examspapers();
            $qbank = new model_newagk_qbank();
            $questions = new model_newagk_questions();
            $paper_model = new model_newagk_paper();
            $leftjoin = array(
                'agk_basic ab' => 'ab.id=agk_exams_papers.basicid',
                'agk_basic_user abu' => 'abu.identity_id=agk_exams_papers.identity_id',
                'agk_paper ap' => 'ap.id=agk_exams_papers.paperId',
            );
            $condit = [
                'agk_exams_papers.id'=>$id];
            if ($identity_id){
                $condit['agk_exams_papers.identity_id']=$identity_id;
            }
            $paperArr = $examspaper_model->selectOne($condit,
                'ap.settings,ap.dbs,ap.name,ap.duration,ap.passScore,ap.totalScore,ap.totalNum,agk_exams_papers.*,ab.basic as basic_name,abu.usertruename,abu.idcard,FROM_UNIXTIME(agk_exams_papers.starttime) as starttime',
                "","",$leftjoin);

            if ($paperArr){
                $question = unserialize($paperArr['question']);
                    //获取每个题的得分数值
                $score_types = array(
                    1=>0,
                    2=>0,
                    3=>0,
                    4=>0,
                    5=>0,
                    'total'=>0,
                );
                $sure_score_types = array(
                    1=>0,
                    2=>0,
                    3=>0,
                    4=>0,
                    5=>0,
                    'total'=>0,
                );
                $paper_setting = $paper_model->selectOne("id in ({$paperArr['paperId']})",'id,settings');
                $setting = unserialize($paper_setting['settings']);
                $setting = $this->arrayValueByKey($setting,0);
                $paperArr_answer= unserialize($paperArr['answer']);//用户的答案
                foreach ($question as $quesK=>$quesV){
                    foreach ($quesV as $esK=>$esV){
                        $question[$quesK][$esK]['select'] = str_replace('#*#','    ',$esV['select']);
                        $sure_score_types[$esV['typeId']]+=$setting[$esV['typeId']][4];
                        $score = $setting[$esV['typeId']][4]?$setting[$esV['typeId']][4]:0;
                        if ($esV['typeId']==4 || $esV['typeId']==5){
                            if ($paperArr_answer[$esV['id']]['answer'][1]=='y' && !empty($paperArr_answer[$esV['id']]) && $paperArr['is_read']==1){

                                $score_types[$esV['typeId']]+=(float)$score;
                                $question[$quesK][$esK]['userscore'] = $score;
                                $question[$quesK][$esK]['score'] = $score;
                                $question[$quesK][$esK]['sure'] = 1;
                                $question[$quesK][$esK]['useranswer'] = $paperArr_answer[$esV['id']]['answer'][0];
                            }else{
                                if ($paperArr['is_read']==2 && ($esV['typeId']==4 || $esV['typeId']==5)){
                                    $score_types[$esV['typeId']] ="人工阅卷";
                                }else{
                                    $score_types[$esV['typeId']] +=0;
                                }
                                $question[$quesK][$esK]['userscore'] = 0;
                                $question[$quesK][$esK]['score'] = $score;
                                $question[$quesK][$esK]['sure'] = 3;//未阅卷
                                $question[$quesK][$esK]['useranswer'] = $paperArr_answer[$esV['id']]['answer'][0]?$paperArr_answer[$esV['id']]['answer'][0]:'未解答！';
                            }
                        }else{
                            if ($esV['answer']==$paperArr_answer[$esV['id']]['answer'] && !empty($paperArr_answer[$esV['id']])){
                                $score_types[$esV['typeId']]+=(float)$score;
                                $question[$quesK][$esK]['userscore'] = $score;
                                $question[$quesK][$esK]['score'] = $score;
                                $question[$quesK][$esK]['sure'] = 1;
                                $question[$quesK][$esK]['useranswer'] = $paperArr_answer[$esV['id']]['answer'];
                            }else{
                                if ($paperArr['is_read']==2 && ($esV['typeId']==4 || $esV['typeId']==5)){
                                    $score_types[$esV['typeId']] ="人工阅卷";
                                }else{
                                    $score_types[$esV['typeId']] +=0;
                                }
                                $question[$quesK][$esK]['userscore'] = 0;
                                $question[$quesK][$esK]['score'] = $setting[$esV['typeId']][4]?$setting[$esV['typeId']][4]:0;
                                $question[$quesK][$esK]['sure'] = 0;
                                $question[$quesK][$esK]['useranswer'] =  $paperArr_answer[$esV['id']]['answer']?$paperArr_answer[$esV['id']]['answer']:'未解答！';
                            }
                        }

                    }
                }
                $single = $question['single'];
                $more = $question['more'];
                $judge = $question['judge'];
                $gapFilling = $question['gapFilling'];
                $subjectivity = $question['subjectivity'];


                $score_types['total'] = (float)$paperArr['modified'];
                $sure_score_types['total'] = (float)$paperArr['totalScore'];


                $single_arr = array_column($single,'typeId');
                $more_arr = array_column($more,'typeId');
                $judge_arr = array_column($judge,'typeId');
                $gapFilling_arr = array_column($gapFilling,'typeId');
                $subjectivity_arr = array_column($subjectivity,'typeId');


                $qbank_name = $qbank->selectOne(['id'=>$paperArr['dbs']],'name');
                $count = count($single_arr)+count($more_arr)+count($judge_arr)+count($gapFilling_arr)+count($subjectivity_arr);
                $datac= ['count'=>$count,
                    'userinfo'=>[
                        'usertruename'=>$paperArr['usertruename'],
                        'idcard'=>$paperArr['idcard'],
                    ],
                    'starttime'=>$paperArr['starttime'],
                    'questype'=>$score_types,
                    'sure_score_types'=>$sure_score_types,
                    'list'=>[
                        '1'=>$single?$single:[],
                        '2'=>$more?$more:[],
                        '3'=>$judge?$judge:[],
                        '4'=>$gapFilling?$gapFilling:[],
                        '5'=>$subjectivity?$subjectivity:[]],
                    'remark'=>$paperArr['remark'],
                    'answer'=>$paperArr_answer?$paperArr_answer:[],
//                    'all_answer'=>array(),
                    'modified'=>$paperArr['modified'],
                    'ispass'=>$paperArr['is_read']==2?"----":($paperArr['modified']>$paperArr['passscore']?"合格":"不合格"),
                    'type'=>($paperArr['type']==1)?"正常":($paperArr['type']==2?"考试异常":"身份异常"),
                    'time'=>$this->secToTime($paperArr['time']),
                    'qbankName'=>$qbank_name['name'],
                    'is_read'=>$paperArr['is_read'],
                    'duration'=>$paperArr['duration'],
                    'totalScore'=>$paperArr['totalScore'],
                    'passScore'=>$paperArr['passScore'],
                    'paperName'=>$paperArr['name'],];
            }else{
                $result->code = 0;
                $result->message = "该试卷已经被删除！";
            }

            $result->message = json_encode($datac);
            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }

	//添加/修改试卷
	public function s_save($data){
		// 对抽题设置进行组合 
		$userid = $data['userid'];
		unset( $data['userid']);

		$qbank = new model_newagk_qbank();
		$qbankDel = $qbank->selectOne(['id'=>$data['dbs']],'name');
		$data['ques_name'] = $qbankDel['name'];
		

		$id = 0;
		if(!empty($data['id'])){
			$id = $data['id'];
			unset($data['id']);
		}
		/**通过管理员id 知道初始平台id***/
		$admins = new model_newagk_adminuser();
		$adminuser = $admins->selectOne(['id'=>$userid],'platform_id,reg,realname');
		//$ob_dw = new DrawQuestion();//这个是抽题类 等唐川写好再改
		//$data['ratio'] = $ob_dw->enRation($ratio);
		
		if(!empty($data['settings'])){
			$data['totalNum']=0;
			foreach($data['settings'] as $vset){
				$data['totalNum'] += $vset[3];
			}
			$settingss = $data['settings'];
			$data['settings'] = serialize($data['settings']);
		} else {
			$data['settings'] = $data['ratio'];
			$settingss = $data['ratio'];
		}
		$data['modifyor'] = $adminuser['realname'];//必须传的用户名
		$data['updateTime'] = $data['modifydate'] = date('Y-m-d H:i:s');
		$drawquestion = new service_drawquestion();
	
			$draw_datas = [];
			if(!empty($settingss[0]) && !empty($settingss[0][0]) && !empty($settingss[0][4]) && !empty($settingss[0][3])  && !empty($settingss[0][5])  ){
				$draw_datas = $drawquestion->randomDrawQues($data['dbs'],$data['settings'],1);
			} else {
				return '抽题规则错误，请检查是否设置抽题分值和抽题数量';	
			}

			if(empty($draw_datas)){
				return '未抽出试题请检查抽题配置';	
			}
		if($data['paperType']=='2'){ //只有普通试卷才写入
			$data['datas'] = serialize($draw_datas);
		}
		$data['poster'] = &$data['modifyor'];
		$data['createdate'] = &$data['modifydate'];
		$data['admin_reg'] = $adminuser['reg']; //必须传的用户reg
		

				
		//使用模型写入，可以在模型中定义更高级的操作
		$model = new model_newagk_paper();
		if($id){
			unset($data['admin_reg']);
			$pid = $model->update(['id'=>$id],$data);
		} else {
			$pid = $model->insert($data);
		}
		return 'y'; //预留如果需要试卷绑定就用下面代码
		$bingding = new model_newagk_platformbingding();
		
		/**通过管理员id 知道初始平台id end***/
		$bingding->insert(['pid'=>$pid,'userId'=>$userid]);
		
		if(!empty($adminuser['platform_id'])){
			$platform = new model_newagk_platform();
			$platform_id = $platform->getChildByPlaformId($adminuser['platform_id'],'id');
			
			$adminuserid = $platformModel->select("platformId in(".implode(',',$platform_id).")","id")->items;
			
			/***循环绑定当前用户上级的id***/
			foreach($adminuserid as $v){
				$bingding->insert(['pid'=>$pid,'userId'=>$v['id']]);
			}
			
		}
		return '试卷配置保存成功';
	}
        
    public function examStatus(AdminPaperRequestDTO $Exam)
    {
        $result = new ResultDO();
        try {

            $filename = $Exam->filename ? $Exam->filename : [];
            $examid = $Exam->id ? explode(',', $Exam->id) : [];
            $platform_id = $Exam->platform_id ? $Exam->platform_id : 0;
			$reg = $Exam->limit ? $Exam->limit : '';
            $model = new model_newagk_paper();
            $id = [0];
            foreach ($examid as $v) {
                $id[] = (int) $v;
            }
			$dwnid = implode("','", $id);
            $condition = "id in('" . $dwnid . "')"; //'admin_reg'=>$reg,
            $res = 0;

            if (!empty($filename)) {
                if (!empty($filename['isdelete']) && $filename['isdelete'] == 'removes') {
                    $model->delete($condition.' and isdelete=1');
					$res=1;
                } else {
					 $result->message = '操作成功';
					if($filename['status']==2 || $filename['status']==3 || $filename['isdelete'] == '1'){
						$doesExist = $model->doesExist($dwnid);
						
						if(!empty($doesExist)){
							$diffId = array_diff($id,$doesExist);
									
			
							$condition = " id in('" . implode("','", $diffId) . "')";

							 $result->message = '操作成功，但存在处于占用状态试卷';
						}
						
						if(!empty($diffId)){
							$res = $model->update($condition, $filename);
													
						} else {
							$result->message = '操作成功，存在处于占用状态试卷';
						}
					} else {
						$res = $model->update($condition, $filename);
					}
													
					
                }
            } 

            if ($res) {
                $result->code = 1;
				
            } else {
                $result->code = 1;
                $result->message = '试卷处于占用状态！';
            }

            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;

            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }
	
	
	//清空回收站
    public function recycleBin(AdminPaperRequestDTO $Exam)
    {
        $result = new ResultDO();
        try {

            $reg = $Exam->filename['reg'] ? $Exam->filename['reg'] : '';
			if($reg==''){
            $result->code = 0;
            $result->message = '缺少必要参数';
            $result->success = true;
            return $result;

			}

            $model = new model_newagk_paper();
            $res = $model->delete("isdelete=1");//admin_reg='{$reg}' and 
                
            if ($res) {
                $result->code = 1;
                $result->message = '操作成功';
            } else {
                $result->code = 0;
                $result->message = '操作失败';
            }

            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;

            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }

    //云试卷列表
     public function cloudlist(AdminPaperRequestDTO $basic)
    {
		$result = new ResultDO();
		$filename = $basic->filename ? $basic->filename : [];
		$qid = $basic->filename['qid'] ?  gdl_lib_BaseUtils::getStr($basic->filename['qid'], 'int') : 0;
		$downid = $basic->filename['id'] ? explode(',',$basic->filename['id']) : '';
		$shareds = $basic->filename['shareds'] ?  gdl_lib_BaseUtils::getStr($basic->filename['shareds'], 'int') : 0;
		
		$typesof = $basic->filename['typesof'] ?  gdl_lib_BaseUtils::getStr($basic->filename['typesof'], 'int') : '';
		$problemet = $basic->filename['problemet'] ?  gdl_lib_BaseUtils::getStr($basic->filename['problemet'], 'string') : ''; 
		$shared = $basic->filename['shared'] ?  gdl_lib_BaseUtils::getStr($basic->filename['shared'], 'string') : '';
		$platform = $basic->filename['platform'] ?  gdl_lib_BaseUtils::getStr($basic->filename['platform'], 'string') : '';
		$title = $basic->filename['title'] ?  gdl_lib_BaseUtils::getStr($basic->filename['title'], 'string') : '';
		$status = $basic->filename['status'] ?  gdl_lib_BaseUtils::getStr($basic->filename['status'], 'string') : '';
		$paper = [];
		$condition = 'isdelete=0 and shared=1 and father=0';
			$platform_id = $platform_id ? gdl_lib_BaseUtils::getStr($platform_id, 'int') : 0;
			//现在还没有启动平台id 所以下面只接差所有
			$modelPlaform = new model_newagk_platform();
			$paper = new model_newagk_paper();
			$qbank = new model_newagk_qbank();
			//名称/云试卷来源关键字

			if($title!=''){
				$inherit = $qbank->select("name like '%{$title}%'",'id')->items;
				$id = [];
				foreach($inherit as $v){
					$id[] = $v['id'];
				}
				$condition .= " and ( name like '%{$title}%' or id like '%{$title}%' ";
				if(!empty($id)) $condition .= ' or dbs in('.implode(',',$id).')';
				$condition .= ' )';
			}

			
			//试卷用途类型
			if($typesof){
				$condition .= ' and puse='.$typesof;
			}
			//抽题方式
			if($problemet=='fixed'){
				$condition .= ' and paperType=2';
			} else if($problemet=='randoms'){
				$condition .= ' and paperType=1';
			}
			
				/**获取当前平台已经继承的试卷id**/
				$inherit = $paper->fatherfo($platform_id);
				/**获取当前平台已经继承的试卷id end**/
			//试卷状态
			if($status=='added'){
				$condition .= ' and father>0';
			} else if($status=='notadd'){
				$notid = implode(',',array_keys($inherit));
				$condition .= " and father=0 and id not in({$notid})";
			} else if($status=='pendin'){
				$condition .= ' and version=1';
			}

			//试卷所属平台
			/*
			if($platform){
				$reg = $modelPlaform->getChildAdminRegByPlaformId($platform_id,$platform);
				$condition .= " and admin_reg in('".implode("','",$reg)."')";
			}
			*/
			
			if($platform){
				$adminreg = $modelPlaform->select("status=1 and reals like '%{$platform}%'",'admin_reg')->items;
				$admin_reg=[1];
				foreach($adminreg as $v){
					$admin_reg[] = $v['admin_reg'];
				}
				if(!empty($admin_reg[0])){
					$condition .= " and admin_reg in('".implode("','",$admin_reg)."')";
				}
			}
			
			
			
			//////////////////
			$page = ($filename['page']-1) * $filename['pagesize'];

            $items = 'id,name,dbs,puse,status,paperType,updateTime,shared,father,version,admin_reg';
			
			if($shareds=='1'){
				$groupBy = ' order by id desc ';
			} else {
				$groupBy = ' order by id desc  limit '.$page.','.$filename['pagesize'];
			}
        
			
			
			if($shareds=='1' && !empty($downid) ){
				$dow_id = [0];
				foreach($downid as $v){
					$dow_id[] = intval($v);
				}
				$condition = ' id in('.implode(',',$dow_id).')';
				
			}
            try {
				$num = $paper->selectOne($condition, 'count(*) num');
                $res = $paper->select($condition, $items, $groupBy)->items;

                //进行平台顶级读取处理

                if (!empty($res)) {
					$qbank_name = $qbank->getListByArgName($platform_id);
					$typesof = ['1'=>'模拟试卷','2'=>'正式试卷','3'=>'公用试卷'];
					$status=['1'=>'正常可用','2'=>'不可用','3'=>'平台禁用'];
					$platform_name = $modelPlaform->getListByArgName($platform_id);
					$papers = $paper->select('isdelete=0','id,name,version')->items;
					$paper_name = [];
					foreach($papers as $vc){
						$paper_name[$vc['id']] = ['name'=>$vc['name'],'version'=>$vc['version']];
					}
					$papersa = [];
					if($shareds=='1' ){
						foreach($res as $v){
							$cloud_staus=1;
							if($v['status']==3){
								$cloud_staus = 4;
							} else if(empty($inherit[$v['id']])){
								$cloud_staus = 3;
							} else if(!empty($inherit[$v['id']]) && $inherit[$v['id']]['version']){
								$cloud_staus = 2;
							}
							 array('ID','试卷名称','试卷来源题库','试卷类型','抽题方式','更新时间','云试卷状态','所属平台');
							$papersa[] = [
										'id'=>$v['id'],
										'paper_name'=>$v['name'],
										'bank_name'=>empty($qbank_name[$v['dbs']]) ? '未知' : $qbank_name[$v['dbs']],
										'typesof'=>$typesof[$v['puse']],
										'paperType'=>$v['paperType']==2 ? '固定抽题' : '随机抽题', //fixed 固定 randoms 随机
										
										'updateTime'=>$v['updateTime'],
										'status_name'=>$status[$v['status']],
										'platform_name'=>empty($platform_name[$v['admin_reg']]) ? '未知' : $platform_name[$v['admin_reg']]
										];
						}
					} else {
						foreach($res as $v){
						$cloud_staus=1;
						if($v['status']==3){
							$cloud_staus = 4;
						} else if(empty($inherit[$v['id']])){
							$cloud_staus = 3;
						} else if(!empty($inherit[$v['id']]) && $inherit[$v['id']]['version']){
							$cloud_staus = 2;
						}
						$papersa[] = [
									'id'=>$v['id'],
									'paper_name'=>$v['name'],
									'bank_name'=>empty($qbank_name[$v['dbs']]) ? '未知' : $qbank_name[$v['dbs']],
									'typesof'=>$typesof[$v['puse']],
									'updateTime'=>$v['updateTime'],
									'status_name'=>$status[$v['status']],
									'status'=>$v['status'],
									'paperType'=>$v['paperType']==2 ? '固定抽题' : '随机抽题', //fixed 固定 randoms 随机
									'replaces'=>empty($inherit[$v['id']]) ? 0 : $inherit[$v['id']]['version'],
									'platform_name'=>empty($platform_name[$v['admin_reg']]) ? '未知' : $platform_name[$v['admin_reg']],
									'part'=>empty($inherit[$v['id']]) ? 0 : 1, //0是可以本地 1是已经在本地
									'cloud_staus' => $cloud_staus,
									];
						}
					}
					if(empty($papersa)){
						$result->data[] = $papersa;
					} else {
                    $result->data = $papersa;
					}
					$result->message = $num['num'];
                    $result->code = 1;

                } else {
                    $result->code = 1;
					 $result->message = 0;
                }
                $result->success = true;
                return $result;
            } catch (Exception $e) {
                $result->success = false;
                $result->code = $e->getCode();
                $result->message = $e->getMessage();
            }
            return $result;

	}
	
	public function addPaper(AdminPaperRequestDTO $Exam){
			 $result = new ResultDO();
        try {
			$examid = $Exam->id ? explode(',',$Exam->id) : [];
			$platform_id  = $Exam->platform_id ? $Exam->platform_id : 0;

			$paper = new model_newagk_paper();
			/**获取当前平台已经继承的试卷id**/
			$inherit = $paper->fatherfo($platform_id);
			/**获取当前平台已经继承的试卷id end**/
			
			$id = [0];
			foreach($examid as $v){
				$id[] = (int)$v;
			}
			
			$condition = "id in('".implode("','",$id)."')";//'admin_reg'=>$reg,
			$notidArr = [0];
			foreach($inherit as $kin=>$vin){
				$notidArr[] = $kin;
			}
			$notid = implode(',',$notidArr);
			$condition .= " and id not in({$notid})";
			$paperDetails = $paper->select($condition, '*')->items;
			foreach($paperDetails as $v){
				$data = [
						'name'=>$v['name'],
						'typesId'=>$v['typesId'],
						'labelId'=>$v['labelId'],
						'puse'=>$v['puse'],
						'dbs'=>$v['dbs'],
						'duration'=>$v['duration'],
						'totalScore'=>$v['totalScore'],
						'passScore'=>$v['passScore'],
						'per'=>$v['per'],
						'paperType'=>$v['paperType'],
						'remark'=>$v['remark'],
						'datas'=>$v['datas'],
						'poster'=>$v['poster'],
						'createdate'=>date('Y-m-d H:i:s'),
						'updateTime'=>date('Y-m-d H:i:s'),
						'modifydate'=>date('Y-m-d H:i:s'),
						'settings'=>$v['settings'],
						///'creditsettingid'=>$v['creditsettingid'],
						'father'=>$v['id'],
						'version'=>0,
						'platform_id'=>$platform_id,
						];
					$paper->insert($data);
			}

			
            if (!empty($paperDetails)) {
                $result->code = 1;
				$result->message = '操作成功';
            } else {
                $result->code = 0;
				$result->message = '操作失败';
            } 

            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;

            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
	}
	
	//更新本地继承的试卷
	public function renewPaper(AdminPaperRequestDTO $Exam){
			 $result = new ResultDO();
        try {
			$id = $Exam->id ? explode(',',$Exam->id) : [];
			$platform_id  = $Exam->platform_id ? $Exam->platform_id : 0;

			$model = new model_newagk_paper();
			/**获取当前平台已经继承的试卷id**/

			$paperDetails = $paper->selectOne('id='.$id, '*');
			  if(!empty($paperDetails)) {
				$data = [
						'name'=>$v['name'],
						'typesId'=>$v['typesId'],
						'labelId'=>$v['labelId'],
						'puse'=>$v['puse'],
						'dbs'=>$v['dbs'],
						'duration'=>$v['duration'],
						'totalScore'=>$v['totalScore'],
						'passScore'=>$v['passScore'],
						'per'=>$v['per'],
						'paperType'=>$v['paperType'],
						'remark'=>$v['remark'],
						'datas'=>$v['datas'],
						'poster'=>$v['poster'],
						'updateTime'=>date('Y-m-d H:i:s'),
						'modifydate'=>date('Y-m-d H:i:s'),
						'settings'=>$v['settings'],
						'version'=>0,

						];
					$paper->update('father='.$v['id'],$data);
			}

			
            if (!empty($paperDetails)) {
                $result->code = 1;
				$result->message = '操作成功';
            } else {
                $result->code = 0;
				$result->message = '操作失败';
            } 

            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;

            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
	}

    /**
     *      把秒数转换为时分秒的格式
     *      @param Int $times 时间，单位 秒
     *      @return String
     */
    private function secToTime($times){
        $result = '00:00:00';
        if ($times>0) {
            $hour = floor($times/3600);
            $minute = floor(($times-3600 * $hour)/60);
            $second = floor((($times-3600 * $hour) - 60 * $minute) % 60);
            $result = ($hour?$hour:"0").'小时'.$minute.'分'.$second."秒";
        }
        return $result;
    }


    /**
     * 转换数组的键值和键名
     * @param $array
     * @param $item
     * @return array
     */
    private function arrayValueByKey($array,$item='id'){
        $arr = array();
        if (!$array){
            return $array;
        }
        foreach ($array as $key=>$value){
            if ($item){
                $arr[$value[$item]] = $value;
            }elseif (is_numeric($item)){
                $arr[$value[$item]] = $value;
            }else{
                $arr[$value['id']] = $value;
            }
        }
        return $arr;
    }
}
